<?php namespace auth;

/**
 * Session
 */

class SessionGuard implements Guard {

    protected $model;#Eloquent Model.

    protected $request;

    protected $guard_config;

    protected $user;

    public function __construct($guard_config=array())
    {
        empty($guard_config)
            ? $this->guard_config = $this->guardConfigDemo()
            : $this->guard_config = $guard_config;
        $this->model = $this->guard_config['model'];
        session_start();
    }

    public function guardConfigDemo()
    {
        return [
            'key'       =>  'user'
            'type'      =>  'session', #session | token
            'storage'   =>  'default', #TODO:Token的存储介质包括redis、file、DB
            'table'     =>  'users',
            'fields'    =>  ['email', 'password'],
            'model'     =>  'App/User::class',
            'gate_group'      =>  ''
        ];
    }

    public function checkRequestParam()
    {
        $request = $this->request;
        // TODO: Return info.
        if (! $request[$this->guard_config['fields'][0]] || ! $request[$this->guard_config['fields'][1]]) {
            return false;
        }
        $this->user = $this->model
            ->table($this->guard_config['table'])
            ->where($this->guard_config['fields'][0], $request[$this->guard_config['fields'][0]])
            ->first();
        if (! $this->user) {
            return false;
        }
        if (! password_verify($request[$this->guard_config['fields'][1]], $this->user->password)) {
            return false;
        }
        return true;
    }

    public function returnAuthResult($request)
    {
        // TODO:session机制、时间以及GC概率自定义
        if (! $this->checkRequestParam($request)) {
            return false;
        }
        $token = $this->makeIdentityToken();

        $_SESSION['zauth'][$this->guard_config['key']] = $this->getPermissionsByGate();
    }

    public function makeIdentityToken()
    {
        // TODO: Implement makeIdentityToken() method.
        return sha1(uniqid());
    }

    public function getPermissionsByGate()
    {
        // TODO: Implement getPermissionsByGate() method.
        Gate::get($this->user);
        return $this->user->$this->guard_config['gate_group'];
    }
}